package mylab.utils.common.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.time.Duration;
import java.util.Map;

public class LocalCacheService<K, V> {

    static final long DEFAULT_MAX_SIZE = 1024 * 10;

    protected Cache<K, V> cache;

    public LocalCacheService() {
        this(DEFAULT_MAX_SIZE);
    }

    public LocalCacheService(long maximumSize) {
        this(CacheBuilder
                .newBuilder()
                .maximumSize(maximumSize)
                .build());
    }

    /**
     * 基于时间过期淘汰机制的缓存
     * <p>
     * 当持续时间为零时，此方法将切换到maximumSize（0），忽略任何其他指定的最大大小或重量
     *
     * @param maximumSize       缓存最大容量
     * @param expireAfterAccess 当缓存项在指定的时间段内没有被读或写就会被回收
     * @param expireAfterWrite  当缓存项在指定的时间段内没有更新就会被回收
     */
    public LocalCacheService(long maximumSize, Duration expireAfterAccess, Duration expireAfterWrite) {
        this(CacheBuilder
                .newBuilder()
                .maximumSize(maximumSize)
                .expireAfterAccess(expireAfterAccess)
                .expireAfterWrite(expireAfterWrite)
                .build());
    }

    protected LocalCacheService(Cache<K, V> cache) {
        this.cache = cache;
    }

    public void clear() {
        cache.invalidateAll();
    }

    public V get(K k) {
        return cache.getIfPresent(k);
    }

    public void put(K key, V value) {
        cache.put(key, value);
    }

    public void remove(K key) {
        cache.invalidate(key);
    }

    public boolean containsKey(K key) {
        return cache.getIfPresent(key) != null;
    }

    public long size() {
        return cache.size();
    }

    public Map<K, V> getMap() {
        return cache.asMap();
    }
}
